package util

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"reflect"
	"strconv"
)

// 获取字符串的MD5
func Md5(str string) string {
	md5Ctx := md5.New()
	md5Ctx.Write([]byte(str))
	cipherStr := md5Ctx.Sum(nil)
	return hex.EncodeToString(cipherStr)
}

// 获取数据类型
func GetObjType(obj interface{}) string {
	t := reflect.TypeOf(obj)
	fmt.Printf("数据类型:%v \n", t)
	return fmt.Sprintf("%v", t)
}

// 字符串转数字，失败则返回默认值
func StringToInt64(str string, def int64) int64 {
	if b, err := strconv.Atoi(str); err == nil {
		return int64(b)
	} else {
		return def
	}
}

// 对象转数字，失败则返回默认值
func ObjToInt64(obj interface{}, def int64) int64 {

	switch value := obj.(type) {
	case string:
		return StringToInt64(value, def)
	case int:
		return int64(value)
	case int8:
		return int64(value)
	case int16:
		return int64(value)
	case int32:
		return int64(value)
	case int64:
		return int64(value)
	case uint:
		return int64(value)
	case uint8:
		return int64(value)
	case uint16:
		return int64(value)
	case uint32:
		return int64(value)
	case uint64:
		return int64(value)
	case float32:
		return int64(value)
	case float64:
		return int64(value)
	default:
		return def
	}

}

// 对象转字符串，失败则返回默认值
func ObjToString(obj interface{}, def string) string {
	switch value := obj.(type) {
	case string:
		return value
	default:
		return def
	}

}
